<template>
  <div class="item-manage-container">
    <div v-show="isShowTree" class="item-manage-container-left">
      <div style="padding: 5px 8px">
        <span style="font-size: 18px; font-weight: bold; padding-right: 16px">区划</span>
        <!-- <span style="color: #c0c4cc">事项目录</span> -->
      </div>
      <el-tree
        v-if="treeData.length"
        class="area-tree"
        :data="treeData"
        :props="defaultProps"
        :default-expanded-keys="defaultExpandedKeys"
        node-key="key"
        highlight-current
        accordion
        @node-click="nodeClick"
        :current-node-key="formInline.areaCode"
      >
        <span class="custom-tree-node" slot-scope="{ data }">
          <img v-if="data.type === 'area'" class="custom-tree-node-img" src="@/assets/img/place.png" />
          <img v-else class="custom-tree-node-img" src="@/assets/img/house.png" />
          <span>{{ data.value }}</span>
        </span>
      </el-tree>
    </div>
    <div v-show="isShowTree" class="menu-in" @click="handleMenu">
      <i class="el-icon-caret-left" style="padding-right: 4px"></i>
      <span>收起目录</span>
    </div>
    <div v-show="!isShowTree" class="menu-out" @click="handleMenu">
      <i class="el-icon-caret-right" style="padding-right: 4px"></i>
      <span>展开目录</span>
    </div>
    <div class="item-manage-container-right">
      <div class="page-header">
        <div class="page-header-title">
          正在操作：
          <span v-for="item in operList" :key="item.id">{{ item.name }}</span>
        </div>
        <div class="page-header-button flex-center">
          <el-button :type="showType === 'icon' ? 'primary' : ''" @click="changeShowType('icon')">
            <div class="flex-center">
              <i class="iconfont icon-tubiao"></i>
              图标展示
            </div>
          </el-button>
          <el-button :type="showType === 'table' ? 'primary' : ''" @click="changeShowType('table')">
            <div class="flex-center">
              <i class="iconfont icon-table"></i>
              列表展示
            </div>
          </el-button>
        </div>
      </div>
      <div class="context search-container">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-row>
            <el-col :span="24">
              <el-form-item style="margin-right: 60px" label="事情名称：">
                <el-input v-model="formInline.thingName" placeholder="请输入名称" clearable></el-input>
              </el-form-item>
              <!-- <el-form-item style="margin-right: 60px" label="实施清单名称：">
                <el-input v-model="formInline.basicCoding" placeholder="请输入实施清单名称" clearable></el-input>
              </el-form-item> -->
              <el-form-item style="margin-right: 60px" label="状态：">
                <el-radio-group v-model="formInline.state">
                  <el-radio label="" border>全部</el-radio>
                  <el-radio :key="item.item_value" :label="item.item_value" border v-for="item in stateList">
                    {{ item.item_text }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item style="float: right">
                <el-button type="primary" @click="onSearch('click')" style="width: 120px">搜索</el-button>
                <el-button type="primary" @click="addItem" style="width: 120px">新建</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div v-show="showType === 'table'" class="tableBox">
        <el-table
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          height="100%"
          @selection-change="handleSelectionChange"
          @row-contextmenu="openContextMenu"
        >
          <el-table-column prop="thingName" label="一件事名称" show-overflow-tooltip>
            <div class="ec-name" slot-scope="scope">
              <img class="tableBox-img" :src="`img/itemManage/${typeIconMap[scope.row.type] || 'thing'}.png`" />
              <span style="margin-left: 10px">{{ scope.row.thingName }}</span>
              <!-- <span class="checkbox-status" :class="'status-content status--' + scope.row.state">{{ scope.row.stateName }}</span> -->
            </div>
          </el-table-column>
          <el-table-column prop="thingId" show-overflow-tooltip label="一件事" width="300"></el-table-column>
          <!-- <el-table-column prop="crossFlag" label="事项名称" width="200"></el-table-column> -->

          <el-table-column prop="areaCode" label="区划" width="150">
            <template slot-scope="scope">
              <span>{{ areaMap[scope.row.areaCode] && areaMap[scope.row.areaCode].value }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态" width="150">
            <template slot-scope="scope">
              <span :class="'status-content status--' + scope.row.state">
                {{ stateMap[scope.row.state] || scope.row.state }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="stateDate" label="状态变更时间" width="200">
            <template slot-scope="scope">
              <span>{{ $moment(scope.row.stateDate).format('YYYY-MM-DD HH:mm:ss') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userId" label="操作人" width="150"></el-table-column>
        </el-table>
      </div>
      <div v-show="showType === 'icon'" class="iconBox" @contextmenu="openContextMenu(null, '', $event)">
        <el-checkbox-group v-if="tableData.length" v-model="checkBoxGroup" size="small">
          <div class="checkbox-group-container none-checkbox">
            <el-checkbox
              v-for="item in tableData"
              :key="item.thingId"
              :label="item"
              @contextmenu.prevent.native="openContextMenu(item, '', $event)"
            >
              <span class="checkbox-group-container-item">
                <img class="checkbox-img" :src="`img/itemManage/${typeIconMap[item.type] || 'thing'}.png`" />
                <div class="checkbox-label">{{ item.thingName }}</div>
                <span class="checkbox-status" :class="'status-content status--' + item.state">
                  {{ stateMap[item.state] }}
                </span>
              </span>
            </el-checkbox>
          </div>
        </el-checkbox-group>
        <div v-else class="none-data">
          <span>暂无数据</span>
        </div>
      </div>
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="formInline.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="formInline.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="total"
        ></el-pagination>
      </div>
    </div>
    <ul v-show="contextmenuVisible" :style="{ left: left + 'px', top: top + 'px' }" class="contextmenu">
      <li v-show="!selectItem" @click="addItem">新建</li>
      <span v-show="selectItem">
        <li @click="editItem">编辑</li>
        <!-- <li @click="showItem">查看</li> -->

        <li v-show="selectItem && selectItem.state === 'D'" @click="submitAudit">提交审核</li>
        <li v-show="selectItem && selectItem.state === 'W'" @click="publish">审核发布</li>
        <li v-show="selectItem && selectItem.state === 'N'" @click="takeEffect">生效</li>
        <li v-show="selectItem && selectItem.state !== 'N'" @click="loseEffect">失效</li>
      </span>
    </ul>
    <addOneThing ref="addOneThing" :areaCode="formInline.areaCode" @addSuccess="onSearch"></addOneThing>
    <publish :visible.sync="publishVisible" :checkData="selectItem" @success="onSearch" />
  </div>
</template>

<script>
  import addOneThing from './components/addOneThing';
  import { getOnething, invalid, takeEffect, stateApproval } from '@/api/onethingManage';
  import { getAreaDepartTree } from '@/api/itemManage';
  import { queryDict } from '@/api/common';
  import publish from './components/publish.vue';

  export default {
    components: {
      addOneThing,
      publish
    },
    data() {
      return {
        operList: [], //正在处理数组
        tableData: [],
        formInline: {
          areaCode: '510000000000',
          basicCoding: '', //基本编码
          thingName: '',
          state: '',
          pageSize: 20,
          pageNum: 1
        },
        total: 0,
        publishVisible: false, //是否显示目录树
        isShowTree: false, //是否显示目录树
        contextmenuVisible: false, //是否显示右键菜单
        left: 0,
        top: 0,
        currentPage: 1,
        treeData: [],
        defaultExpandedKeys: [],
        defaultProps: {
          children: 'children',
          label: 'value'
        },
        checkBoxGroup: [], //批量选中数组
        showType: 'icon',
        selectItem: null,
        visible: {
          implementList: false
        },
        typeIconMap: {},
        areaMap: {},
        stateList: [],
        stateMap: {
          N: '失效',
          Y: '生效'
        }
      };
    },
    watch: {
      contextmenuVisible(value) {
        if (value) {
          document.body.addEventListener('click', this.closeContextMenu);
        } else {
          document.body.removeEventListener('click', this.closeContextMenu);
        }
      }
    },
    mounted() {
      this.onSearch('click');
      this.getAreaDepartTree(); //获取区域信息
      this.getEventStateList(); //获取值表
    },
    methods: {
      //事项状态
      async getEventStateList() {
        const { data } = await queryDict({
          dict: 'matters_state'
        });
        if (data.success) {
          this.stateList = data.result;
          const tempMap = {};
          data.result.forEach((e) => {
            tempMap[e.item_value] = e.item_text;
          });
          this.stateMap = tempMap;
        }
      },
      onSearch(type) {
        this.operList = this.operList.length ? [this.operList[0]] : [];
        if (type === 'click') {
          this.formInline.pageNum = 1;
        }
        this.fetchDataList();
      },
      // 获取表单列表
      async fetchDataList() {
        const { data } = await getOnething(this.formInline);
        if (data.code === 200) {
          const { current, size, total, records } = data.result || {};
          this.tableData = records;
          this.formInline.pageNum = current;
          this.formInline.pageSize = size;
          this.total = total;
        }
      },

      nodeClick(node) {
        this.formInline.areaCode = node.key;
        this.formInline.pageNum = 1;
        this.operList = [
          {
            id: node.key,
            name: node.value
          }
        ];
        this.onSearch();
      },
      handleSizeChange(val) {
        this.formInline.pageSize = val;
        this.formInline.pageNum = 1;
        this.onSearch();
      },
      handleCurrentChange(val) {
        this.formInline.pageNum = val;
        this.onSearch();
      },
      handleSelectionChange(val) {
        this.checkBoxGroup = val;
      },
      handleMenu() {
        this.isShowTree = !this.isShowTree;
      },
      changeShowType(type) {
        if (this.showType === type) return;
        else {
          this.showType = type;
          //清空多选项
          this.checkBoxGroup = [];
        }
      },
      closeContextMenu() {
        this.contextmenuVisible = false;
      },
      openContextMenu(item, column, e) {
        e.stopPropagation();
        e.preventDefault();
        const menuMinWidth = 105;
        const menuMinHieght = item ? 100 : 30;
        const offsetLeft = this.$el.getBoundingClientRect().left; // container margin left
        const offsetWidth = this.$el.offsetWidth; // container width
        const offsetHeight = this.$el.offsetHeight; // container width
        const maxLeft = offsetWidth - menuMinWidth; // left boundary
        const maxTop = offsetHeight - menuMinHieght; // left boundary
        const left = e.clientX - offsetLeft + 15; // 15: margin right
        const top = e.clientY - 90;
        this.left = left > maxLeft ? maxLeft : left;
        // 400
        this.top = top > maxTop ? maxTop : top;
        this.contextmenuVisible = true;
        this.selectItem = item; //右键选中的item
      },
      //获取区域信息
      async getAreaDepartTree() {
        // 5的树就只有自己的区划和自己的部门。4的树有自己的区划及下级区划及对应的各级部门
        let areaCode = '510000000000';
        const { data } = await getAreaDepartTree(areaCode, false);
        if (data.code === 200) {
          this.treeData = [data.result];
          let firstNode = this.treeData && this.treeData[0];
          this.defaultExpandedKeys = [firstNode.key];
          this.formInline.areaCode = firstNode.key;
          this.areaMap = this.transformAreaMap(this.treeData);
          this.operList = [
            {
              id: firstNode.key,
              name: firstNode.value
            }
          ];
        }
      },
      transformAreaMap(treeData) {
        const tempMap = {};
        function transform(data, prePath, preValue) {
          data.forEach((e) => {
            let fullPath = [...prePath, e.key];
            let fullValue = [...preValue, e.value];
            tempMap[e.key] = {
              value: e.value,
              fullValue,
              fullPath
            };
            if (e.children && e.children.length) {
              transform(e.children, fullPath, fullValue);
            }
          });
        }
        transform(treeData, [], []);
        return tempMap;
      },
      //新建
      addItem() {
        this.$refs.addOneThing.isEdit = false;
        this.$refs.addOneThing.showDialog = true;
        this.$refs.addOneThing.getThingDetails();
      },
      //编辑
      editItem() {
        this.$refs.addOneThing.isEdit = true;
        this.$refs.addOneThing.showDialog = true;
        this.$refs.addOneThing.getThingDetails(this.selectItem.thingId);
      },
      //查看
      showItem() {},
      //审核发布
      async publish() {
        this.publishVisible = true;
      },
      //提交审核
      async submitAudit() {
        // const { state } = this.selectItem;
        // if (state !== 'D') {
        //   this.$message.info('请在暂存状态下提交审核');
        //   return;
        // }
        this.$prompt('请输入提交审核原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (val) => {
            if (!val) {
              return '请输入审核原因';
            }
          }
        })
          .then(async ({ value }) => {
            const { data } = await stateApproval({
              thingId: this.selectItem.thingId,
              reason: value
            });
            data.code === 200 && this.$message.success('提交审核成功！');

            this.onSearch();
          })
          .catch(() => {});
      },
      async takeEffect() {
        this.$prompt('请输入生效原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (val) => {
            if (!val) {
              return '请输入原因';
            }
          }
        })
          .then(async ({ value }) => {
            const { data } = await takeEffect({
              thingId: this.selectItem.thingId,
              reason: value
            });
            data.code === 200 && this.$message.success('生效成功！');
            this.onSearch();
          })
          .catch(() => {});
      },
      async loseEffect() {
        this.$prompt('请输入失效原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (val) => {
            if (!val) {
              return '请输入原因';
            }
          }
        })
          .then(async ({ value }) => {
            const { data } = await invalid({
              thingId: this.selectItem.thingId,
              reason: value
            });
            data.code === 200 && this.$message.success('失效成功！');
            this.onSearch();
          })
          .catch(() => {});
      },

      openAddThing() {
        this.$refs.addOneThing.showDialog = true;
      }
    }
  };
</script>
